package cn.com.vs.api;

import java.util.Calendar;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.lang3.StringUtils;

import cn.com.vs.model.Activities;
import cn.com.vs.model.ActivityApplicationBriefList;
import cn.com.vs.model.CreateSportsDataStaus;
import cn.com.vs.model.GeneralJSONResult;
import cn.com.vs.model.RegistrationList;
import cn.com.vs.model.SportsDataList;
import cn.com.vs.model.SportsRecordInfo;
import cn.com.vs.model.Status;
import cn.com.vs.service.ActivityService;
import cn.com.vs.service.ActivityService.RetCode;
import cn.com.vs.service.domain.Activity;
import cn.com.vs.service.domain.ApplicationBrief;
import cn.com.vs.service.domain.Registration;
import cn.com.vs.service.domain.SportsData;
import cn.com.vs.service.domain.SportsDataDetail;
import cn.com.vs.service.domain.SportsDataRecordInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Path("/api") 
public class ActivityApi {
	
	String activityRequired[]={"title","location","digest","content","maxMembers","type","status","enableChat"};
	String trackDataRequired[]={"token","type","startTime","duration","timezone","distance","elapsedduration","calories"};
	/**
	 * 创建活动
	 * @param account
	 * @param actname
	 * @param token
	 * @param activityConfig
	 * @return
	 */
	@POST  
	@Path("/{account}/activity")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String createActivity(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("activity") String data)
	{
		GeneralJSONResult st = new GeneralJSONResult();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st.toString();
		}
		Integer userid = accountInfo.getInteger("id");
		if( StringUtils.isEmpty(data))
		{
			st.setOk(false);
			st.setMessage("data数据不能为空");
			return st.toString();
		}
		try{
			JSONObject activityConfig = JSONObject.parseObject(data);
			String result = ApiUtils.validateJSONRequiredField(activityConfig,activityRequired);
			if( result != null ){
				st.setOk(false);
				st.setMessage(result);
				return st.toString();
			}
			RetCode ret = ActivityService.getInstance().createActivity(userid, account,activityConfig);
			if( ret == RetCode.OK )
			{
				Integer status = activityConfig.getInteger("status");
				if( status == 1 ){
					Integer activityID = activityConfig.getInteger("id");
					Activity act = ActivityService.getInstance().getActivity(activityID);
					st.setData( (JSON)JSON.toJSON(act) );
				}
				st.setOk(true);
			}else{
				st.setOk(false);
				st.setMessage(ret.getDesc());
			}
			return st.toString();
		}catch(Exception e){
			st.setOk(false);
			st.setMessage("data数据不是有效的JSON格式");
			return st.toString();
		}
	}
	
	/**
	 * 更新活动
	 * @param account
	 * @param actname
	 * @param token
	 * @param activityConfig
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/update")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String updateActivity(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("activity") String data)
	{
		GeneralJSONResult st = new GeneralJSONResult();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st.toString();
		}
		Integer userid = accountInfo.getInteger("id");
		if( StringUtils.isEmpty(data))
		{
			st.setOk(false);
			st.setMessage("data数据不能为空");
			return st.toString();
		}
		try{
			JSONObject activityConfig = JSONObject.parseObject(data);
			String result = ApiUtils.validateJSONRequiredField(activityConfig,activityRequired);
			if( result != null ){
				st.setOk(false);
				st.setMessage(result);
				return st.toString();
			}
			RetCode ret = ActivityService.getInstance().updateActivity(userid, account,activityConfig);
			if( ret == RetCode.OK )
			{
				st.setOk(true);
			}else{
				st.setOk(false);
				st.setMessage(ret.getDesc());
			}
			return st.toString();
		}catch(Exception e){
			st.setOk(false);
			st.setMessage("data数据不是有效的JSON格式");
			return st.toString();
		}
	}
	
	/**
	 * 删除创建的活动
	 * @param account
	 * @param token
	 * @param actid
	 * @return
	 */
	@DELETE  
	@Path("/{account}/activity")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Status deleteActivity(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("activityid") String actid)
	{
		Status st = new Status();
		Boolean ret = ApiUtils.checkToken(token, account);
		if( !ret ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		RetCode res = ActivityService.getInstance().deleteActivity( Integer.parseInt(actid) );
		if( res == RetCode.OK )
		{
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage(res.getDesc());
		}
		return st;
	}
	
	/**
	 * 获取我创建的活动
	 * @param account
	 * @param token
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/myactivities")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Activities getMyActivities(@PathParam("account") String account,
			@FormParam("token") String token ,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		Activities st = new Activities();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<Activity> res = ActivityService.getInstance().getMyActivites(userid, Integer.parseInt(from), limit!=null?Integer.parseInt(limit):null);
		if( res !=null )
		{
			st.setData(res);
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 获取当前可用的所有活动列表
	 * @param account
	 * @param token
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Activities getActivities(@PathParam("account") String account,
			@FormParam("token") String token ,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		Activities st = new Activities();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<Activity> res = ActivityService.getInstance().getActivites(userid, Integer.parseInt(from), limit!=null?Integer.parseInt(limit):null);
		if( res !=null )
		{
			st.setData(res);
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	

	/**
	 * 搜索本地活动
	 * @param account
	 * @param token
	 * @param city
	 * @param keywords
	 * @param type
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/local")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Activities getLocalActivities(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("city") String city ,
			@FormParam("keywords") String keywords ,
			@FormParam("type") String type,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		Activities st = new Activities();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( !StringUtils.isBlank(keywords) && keywords.length()<2 )
		{
			st.setOk(false);
			st.setMessage("keywords长度至少大于2个字符");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<Activity> res = ActivityService.getInstance().searchLocalActivites(userid, keywords,city,
				type==null?null:Integer.valueOf(type),Integer.parseInt(from), limit!=null?Integer.valueOf(limit):null);
		if( res !=null )
		{
			st.setData(res);
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 搜索附近的活动
	 * @param account
	 * @param token
	 * @Param keywords
	 * @param center
	 * @param radius
	 * @param type
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/around")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Activities getAroundActivities(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("keywords") String keywords ,
			@FormParam("center") String center ,
			@DefaultValue("3000") @FormParam("radius") String radius ,
			@FormParam("type") String type,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		Activities st = new Activities();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( !StringUtils.isBlank(keywords) && keywords.length()<2 )
		{
			st.setOk(false);
			st.setMessage("keywords长度至少大于2个字符");
			return st;
		}
		if( StringUtils.isBlank(center) || !center.contains(",") ){
			st.setOk( false );
			st.setMessage("center不能为空或无效");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<Activity> res = ActivityService.getInstance().searchAroundActivites(userid, center,Integer.valueOf(radius),
				keywords,type==null?null:Integer.valueOf(type),Integer.parseInt(from), limit!=null?Integer.valueOf(limit):null);
		if( res !=null )
		{
			st.setData(res);
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	@POST  
	@Path("/{account}/activity/region")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Activities getRegionActivities(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("keywords") String keywords ,
			@FormParam("region") String region ,
			@FormParam("type") String type,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		Activities st = new Activities();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( !StringUtils.isBlank(keywords) && keywords.length()<2 )
		{
			st.setOk(false);
			st.setMessage("keywords长度至少大于2个字符");
			return st;
		}
		if( StringUtils.isBlank(region) || !region.contains(",") ){
			st.setOk( false );
			st.setMessage("region不能为空或无效");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<Activity> res = ActivityService.getInstance().searchRegionActivites(userid, region,
				keywords,type==null?null:Integer.valueOf(type),Integer.parseInt(from), limit!=null?Integer.valueOf(limit):null);
		if( res !=null )
		{
			st.setData(res);
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 活动报名
	 * @param account
	 * @param token
	 * @param activityid
	 * @param msg
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/regist")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Status registActivities(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("activityid") String activityid,
			@FormParam("msg") String msg
			)
	{
		Status st = new Status();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( StringUtils.isBlank(activityid)){
			st.setOk(false);
			st.setMessage("activityid不能为空");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		RetCode ret = ActivityService.getInstance().registration(Integer.valueOf(activityid), 
				userid, msg);
		if( ret == RetCode.OK )
		{
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage(ret.getDesc());
		}
		return st;
	}
	
	/**
	 * 查看活动报名成员
	 * @param account
	 * @param token
	 * @param activityid
	 * @param status
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/members")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public RegistrationList activityMembers(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("activityid") String activityid,
			@FormParam("status") String status,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit
			)
	{
		RegistrationList st = new RegistrationList();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( StringUtils.isBlank(activityid)){
			st.setOk(false);
			st.setMessage("activityid不能为空");
			return st;
		}
		List<Registration> result = ActivityService.getInstance().getRegistrations(Integer.valueOf(activityid),
				StringUtils.isNotEmpty(status)?Integer.valueOf(status):null,
				from!=null?Integer.valueOf(from):null, limit!=null?Integer.valueOf(limit):null );
		if( result != null )
		{
			st.setData(result);
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取报名数据异常");
		}
		return st;
	}
	
	/**
	 * 确认报名
	 * @param account
	 * @param token
	 * @param activityid
	 * @param regid
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/confirm")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Status confirmApplication(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("activityid") String activityid,
			@FormParam("registid") String regid)
	{
		Status st = new Status();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( StringUtils.isBlank(activityid)){
			st.setOk(false);
			st.setMessage("activityid不能为空");
			return st;
		}
		if( StringUtils.isBlank(regid)){
			st.setOk(false);
			st.setMessage("registid不能为空");
			return st;
		}
		Integer actid = Integer.valueOf(activityid);
		Integer userid = accountInfo.getInteger("id");
		Activity act = ActivityService.getInstance().getActivity(actid);
		if( act == null ){
			st.setOk(false);
			st.setMessage("无效的活动id");
			return st;
		}
		if( act.getAuthorid() != userid ){
			st.setOk(false);
			st.setMessage("只有活动创建则具有审核权限");
			return st;
		}
		boolean ret = ActivityService.getInstance().confirmMemberApplication(actid, Integer.valueOf(regid));
		if( ret )
		{
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("确认报名异常");
		}
		return st;
	}
	
	/**
	 * 取消报名
	 * @param account
	 * @param token
	 * @param activityid
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/cancel")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Status cancelApplication(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("activityid") String activityid)
	{
		Status st = new Status();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( StringUtils.isBlank(activityid)){
			st.setOk(false);
			st.setMessage("activityid不能为空");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		boolean ret = ActivityService.getInstance().cancelApplication(Integer.valueOf(activityid), userid );
		if( ret )
		{
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("取消报名异常");
		}
		return st;
	}
	
	/**
	 * 获取参加的活动历史列表
	 * @param account
	 * @param token
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/history")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public ActivityApplicationBriefList activiyHistory(@PathParam("account") String account,
			@FormParam("token") String token ,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		ActivityApplicationBriefList st = new ActivityApplicationBriefList();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<ApplicationBrief> result = ActivityService.getInstance().getActivityHistory(userid, from!=null?Integer.valueOf(from):null,
				limit!=null?Integer.valueOf(limit):null);
		if( result != null )
		{
			st.setData( result );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取参加的活动列表异常");
		}
		return st;
	}
	
	/**
	 * 获取参加的活动历史列表
	 * @param account
	 * @param token
	 * @param from
	 * @param limit
	 * @return
	 */
	@POST  
	@Path("/{account}/activity/myActivityTracker")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Activities myActivityTracker(@PathParam("account") String account,
			@FormParam("token") String token ,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		Activities st = new Activities();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		Integer userid = accountInfo.getInteger("id");
		List<Activity> result = ActivityService.getInstance().getJoinedActivity(userid, from!=null?Integer.valueOf(from):null,
				limit!=null?Integer.valueOf(limit):null);
		if( result != null )
		{
			st.setData( result );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取参加的活动列表异常");
		}
		return st;
	}
	
	/**
	 * 创建运动数据
	 * @param account
	 * @param params
	 * @return
	 */
	@POST  
	@Path("/{account}/sportsdata")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public CreateSportsDataStaus createSportsData(
			@PathParam("account") 
			String account,
			MultivaluedMap<String, String> params)
	{
		CreateSportsDataStaus st = new CreateSportsDataStaus();
		String res = ApiUtils.validateJSONRequiredField( params, trackDataRequired);
		if( res != null ){
			st.setOk( false );
			st.setMessage(res);
			return st;
		}
		String token = params.getFirst("token");
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( StringUtils.isNotBlank(params.getFirst("userid")) ){
			if( !ApiUtils.isWechatUser( accountInfo ) ){
				st.setOk(false);
				st.setMessage("权限不足");
				return st;
			}
		}
		Integer uid = accountInfo.getInteger("id");
		String userid = params.getFirst("userid");
		String device = params.getFirst("device");
		String k1bests = params.getFirst("k1bests");
		String k5bests = params.getFirst("k5bests");
		String k10bests = params.getFirst("k10bests");
		String halfbests = params.getFirst("halfbests");
		String marathonbests = params.getFirst("marathonbests");
		RetCode ret = ActivityService.getInstance().createSportsData(
				StringUtils.isBlank(userid)?uid:Integer.valueOf(userid), 
				params.getFirst("type"), 
				params.getFirst("matchName"), 
				params.getFirst("memo"), 
				Long.parseLong(params.getFirst("startTime")), 
				Long.parseLong(params.getFirst("duration")), 
				Long.parseLong(params.getFirst("elapsedduration")),
				params.getFirst("timezone"), 
				Double.valueOf(params.getFirst("distance")), 
				Integer.valueOf(params.getFirst("calories")),
				StringUtils.isBlank(device)?"APP":device, 
				params.getFirst("metrics"),
				StringUtils.isBlank(k1bests)?0:Integer.valueOf(params.getFirst("k1bests")),
				StringUtils.isBlank(k5bests)?0:Integer.valueOf(params.getFirst("k5bests")),
				StringUtils.isBlank(k10bests)?0:Integer.valueOf(params.getFirst("k10bests")),
				StringUtils.isBlank(halfbests)?0:Integer.valueOf(params.getFirst("halfbests")),
				StringUtils.isBlank(marathonbests)?0:Integer.valueOf(params.getFirst("marathonbests")),
				params.getFirst("uuid"),
				st
				);
		if( ret == RetCode.OK )
		{
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage(ret.getDesc());
		}
		return st;
	}
	
	/**
	 * 获取运动数据列表
	 * @param account
	 * @param token
	 * @param sort
	 * @param order
	 * @param from
	 * @return
	 */
	@POST  
	@Path("/{account}/sportsdata/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public SportsDataList getSportsData(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("filter") String filter,
			@FormParam("sort") String sort,
			@FormParam("order") String order,
			@FormParam("userid") String userid,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		SportsDataList st = new SportsDataList();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		
		Integer uid = accountInfo.getInteger("id");
		List<SportsData> result = ActivityService.getInstance().getSportsData(
				StringUtils.isBlank(userid)?uid:Integer.parseInt(userid),
				filter, sort, order, 
				Integer.parseInt(from),StringUtils.isBlank(limit)?null:Integer.valueOf(limit));
		if( result != null )
		{
			st.setData( result );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 获取运动数据列表
	 * @param account
	 * @param token
	 * @param sort
	 * @param order
	 * @param from
	 * @return
	 */
	@POST  
	@Path("/{account}/sportsdata/sync")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public SportsDataList syncSportsData(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("filter") String filter,
			@FormParam("sort") String sort,
			@FormParam("order") String order,
			@FormParam("userid") String userid,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		SportsDataList st = new SportsDataList();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		
		Integer uid = accountInfo.getInteger("id");
		List<SportsData> result = ActivityService.getInstance().syncSportsData(
				StringUtils.isBlank(userid)?uid:Integer.parseInt(userid),
				filter, sort, order, 
				Integer.parseInt(from),StringUtils.isBlank(limit)?null:Integer.valueOf(limit));
		if( result != null )
		{
			st.setData( result );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 返回数据明细
	 * @param account
	 * @param token
	 * @param dataid
	 * @return
	 */
	@POST  
	@Path("/{account}/sportsdata/detail")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String getSportsDataDetail(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("dataid") String dataid,
			@FormParam("userid") String userid)
	{
		GeneralJSONResult st = new GeneralJSONResult();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st.toString();
		}
		
		Integer uid = accountInfo.getInteger("id");
		SportsDataDetail result = ActivityService.getInstance().getSportsDataDetail(
				StringUtils.isBlank(userid)?uid:Integer.valueOf(userid),
				Integer.parseInt(dataid) );
		if( result != null )
		{
			st.setData( (JSON)JSON.toJSON(result) );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st.toString();
	}
	
	/**
	 * 查看运动数据纪录
	 * @param account
	 * @param token
	 * @param userid
	 * @return
	 */
	@POST  
	@Path("/{account}/sportsdata/recordinfo")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public SportsRecordInfo getSportsDataRecordInfo(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("userid") String userid)
	{
		SportsRecordInfo st = new SportsRecordInfo();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		Integer uid = accountInfo.getInteger("id");
		SportsDataRecordInfo result = ActivityService.getInstance().getSportsDataRecordInfo(
				StringUtils.isNotBlank(userid)?Integer.valueOf(userid):uid);
		if( result != null )
		{
			st.setData( result );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 查看运动数据纪录历史
	 * @param account
	 * @param token
	 * @param userid
	 * @return
	 */
	@POST  
	@Path("/{account}/sportsdata/recordlist")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public SportsDataList getSportsRecordList(@PathParam("account") String account,
			@FormParam("token") String token,
			@FormParam("userid") String userid,
			@FormParam("type") String type,
			@DefaultValue("0") @FormParam("from") String from,
			@FormParam("limit") String limit)
	{
		SportsDataList st = new SportsDataList();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}

		Integer uid = accountInfo.getInteger("id");
		List<SportsData> result = ActivityService.getInstance().getSportsDataRecordList(
				StringUtils.isBlank(userid)?uid:Integer.parseInt(userid),
				StringUtils.isBlank(type)?"1k":type,
				Integer.parseInt(from),
				StringUtils.isBlank(limit) ? null : Integer.valueOf(limit));
		if( result != null )
		{
			st.setData( result );
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st;
	}
	
	/**
	 * 删除运动数据
	 * @param account
	 * @param token
	 * @param userid
	 * @return
	 */
	@DELETE 
	@Path("/{account}/sportsdata")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Status deleteSportsData(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("dataid") String dataid,
			@FormParam("userid") String userid
			)
	{
		Status st = new Status();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st;
		}
		if( StringUtils.isBlank(dataid) || !StringUtils.isNumeric(dataid) ){
			st.setOk(false);
			st.setMessage("dataid不能为空或dataid不是一个数字");
			return st;
		}
		if( StringUtils.isNotBlank(userid) ){
			if( !ApiUtils.isWechatUser( accountInfo ) ){
				st.setOk(false);
				st.setMessage("权限不足");
				return st;
			}
		}
		Integer uid = accountInfo.getInteger("id");
		RetCode result = ActivityService.getInstance().deleteSportsData(
				StringUtils.isBlank(userid)?uid:Integer.valueOf(userid), Integer.valueOf(dataid) );
		if( result == RetCode.OK )
		{
			st.setOk(true);
		}else{
			st.setOk(false);
			st.setMessage(result.getDesc());
		}
		return st;
	}
	
	/**
	 * 最近12个月的distance列表
	 * @param account
	 * @param token
	 * @param type
	 * @return
	 */
	@POST
	@Path("/{account}/sportsdata/latest")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String getLatestYearDistanceData(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("type") String type,
			@FormParam("offset") String offset,
			@FormParam("userid") String userid)
	{
		GeneralJSONResult st = new GeneralJSONResult();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st.toString();
		}
		if( StringUtils.isBlank(type) ){
			st.setOk(false);
			st.setMessage("type不能为空");
			return st.toString();
		}
		if( StringUtils.isNotBlank(userid) ){
			if( !ApiUtils.isWechatUser( accountInfo ) ){
				st.setOk(false);
				st.setMessage("权限不足");
				return st.toString();
			}
		}
		Integer uid = accountInfo.getInteger("id");
		JSONArray result = ActivityService.getInstance().getLatestYearDistanceData(
				StringUtils.isBlank(userid)?uid:Integer.parseInt(userid), 
				type,offset);
		if( result != null )
		{
			st.setOk(true);
			st.setData(result);;
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st.toString();
	}
	
	/**
	 * 查询任意用户distance汇总排名
	 * @param account
	 * @param token
	 * @param userid
	 * @param begin
	 * @param end
	 * @param type
	 * @return
	 */
	@POST
	@Path("/{account}/sportsdata/rank")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String getDistanceRankData(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("userid") String userid,
			@FormParam("groupid") String gpid,
			@FormParam("begin") String begin,
			@FormParam("end") String end,
			@FormParam("type") String type,
			@FormParam("iscontacts") String iscontacts,
			@FormParam("fromIndex") String fromIndex,
			@FormParam("limit") String limit)
	{
		GeneralJSONResult st = new GeneralJSONResult();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st.toString();
		}
		if( StringUtils.isBlank(type) ){
			st.setOk(false);
			st.setMessage("type属性不能为空");
			return st.toString();
		}
//		if( StringUtils.isNotBlank(userid) ){
//			if( !ApiUtils.isWechatUser( accountInfo ) ){
//				st.setOk(false);
//				st.setMessage("权限不足");
//				return st.toString();
//			}
//		}
		Integer endTime = null;
		Integer beginTime = null;
		if( StringUtils.isBlank(begin) )
			beginTime = 0;
		else if( !StringUtils.isNumeric(begin) )
			beginTime = ApiUtils.Time2UnixTimestamp(begin);
		else
			beginTime = Integer.valueOf(begin);
		if( StringUtils.isBlank(end) )
			endTime = (int)Calendar.getInstance().getTimeInMillis()/1000;
		else if( !StringUtils.isNumeric(end) )
			endTime = ApiUtils.Time2UnixTimestamp(end);
		else
			endTime = Integer.valueOf(end);
		Integer uid = accountInfo.getInteger("id");
		JSONArray result = ActivityService.getInstance().getRank(
				StringUtils.isBlank(userid)?uid:Integer.valueOf(userid),
				StringUtils.isBlank(gpid)?null:Integer.valueOf(gpid),
				beginTime, endTime, type,
				StringUtils.isBlank(iscontacts)?null:Integer.valueOf(iscontacts),
				StringUtils.isBlank(fromIndex)?null:Integer.valueOf(fromIndex),
				StringUtils.isBlank(limit)?null:Integer.valueOf(limit));
		if( result != null )
		{
			st.setOk(true);
			st.setData(result);;
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st.toString();
	}
	
	/**
	 * 区间距离统计
	 * @param account
	 * @param token
	 * @param userid
	 * @param begin
	 * @param end
	 * @param type
	 * @return
	 */
	@POST
	@Path("/{account}/sportsdata/idstat")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String getIntervalDistanceStatData(@PathParam("account") String account,
			@FormParam("token") String token ,
			@FormParam("cond") String cond,
			@FormParam("type") String type,
			@FormParam("userid") String userid)
	{
		GeneralJSONResult st = new GeneralJSONResult();
		JSONObject accountInfo = ApiUtils.checkAndGetUserInfo(token, account);
		if( accountInfo == null ){
			st.setOk(false);
			st.setMessage("invalid token");
			return st.toString();
		}
		if( StringUtils.isBlank(type) ){
			st.setOk(false);
			st.setMessage("type属性不能为空");
			return st.toString();
		}
		if( StringUtils.isBlank(cond) ){
			st.setOk(false);
			st.setMessage("cond属性不能为空");
			return st.toString();
		}
		if( StringUtils.isNotBlank(userid) ){
			if( !ApiUtils.isWechatUser( accountInfo ) ){
				st.setOk(false);
				st.setMessage("权限不足");
				return st.toString();
			}
		}
		Integer uid = accountInfo.getInteger("id");
		JSONArray result = ActivityService.getInstance().getDistanceStatistics(
				StringUtils.isBlank(userid)?uid:Integer.valueOf(userid), cond, type);
		if( result != null )
		{
			st.setOk(true);
			st.setData(result);;
		}else{
			st.setOk(false);
			st.setMessage("获取数据异常");
		}
		return st.toString();
	}
}
